#!/usr/bin/env bash

# Copyright 2021 Flant JSC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

source /shell_lib.sh

function __config__() {
  cat <<EOF
configVersion: v1
kubernetes:
  - name: cluster_config
    apiVersion: v1
    kind: Secret
    queue: "cache-cluster-config"
    executeHookOnEvent: []
    executeHookOnSynchronization: false
    keepFullObjectsInMemory: false
    namespace:
      nameSelector:
        matchNames: ["kube-system"]
    nameSelector:
      matchNames:
        - d8-provider-cluster-configuration
    jqFilter: '.data."cloud-provider-cluster-configuration.yaml" // ""'
kubernetesCustomResourceConversion:
  - name: alpha1_to_alpha2
    crdName: nodegroups.deckhouse.io
    conversions:
    - fromVersion: deckhouse.io/v1alpha1
      toVersion: deckhouse.io/v1alpha2
  - name: alpha2_to_alpha1
    crdName: nodegroups.deckhouse.io
    conversions:
    - fromVersion: deckhouse.io/v1alpha2
      toVersion: deckhouse.io/v1alpha1
  - name: alpha2_to_v1
    includeSnapshotsFrom: ["cluster_config"]
    crdName: nodegroups.deckhouse.io
    conversions:
    - fromVersion: deckhouse.io/v1alpha2
      toVersion: deckhouse.io/v1
  - name: v1_to_alpha2
    crdName: nodegroups.deckhouse.io
    conversions:
    - fromVersion: deckhouse.io/v1
      toVersion: deckhouse.io/v1alpha2
EOF
}

function __on_conversion::alpha1_to_alpha2() {
  if converted=$(context::jq -r '.review.request.objects//[] | map(
     if .apiVersion ==  "deckhouse.io/v1alpha1" then
       .apiVersion = "deckhouse.io/v1alpha2" |
       if .spec.docker then .spec.cri.docker = .spec.docker end |
       del(.kubernetesVersion) |
       del(.spec.docker) |
       del(.static)
     else . end
  )')
  then
    cat <<EOF >"$CONVERSION_RESPONSE_PATH"
{"convertedObjects": $converted}
EOF
  else
    cat <<EOF >"$CONVERSION_RESPONSE_PATH"
{"failedMessage":"Conversion of nodegroups.deckhouse.io failed"}
EOF
  fi
}

function __on_conversion::alpha2_to_alpha1() {
  if converted=$(context::jq -r '.review.request.objects//[] | map(
     if .apiVersion ==  "deckhouse.io/v1alpha2" then
       .apiVersion = "deckhouse.io/v1alpha1" |
       if .spec.cri.docker then .spec.docker = .spec.cri.docker end |
       del(.spec.cri.docker)
     else . end
  )')
  then
    cat <<EOF >"$CONVERSION_RESPONSE_PATH"
{"convertedObjects": $converted}
EOF
  else
    cat <<EOF >"$CONVERSION_RESPONSE_PATH"
{"failedMessage":"Conversion of nodegroups.deckhouse.io failed"}
EOF
  fi
}


function __on_conversion::alpha2_to_v1() {
  cluster_config_json="{}"
  if context::jq -er '.snapshots.cluster_config[0].filterResult' >/dev/null; then
    cluster_config_json="$(context::jq -r '.snapshots.cluster_config[0].filterResult' | base64 -d | yq eval -I0 -j)"
  fi

  # shellcheck disable=SC2016
  if converted=$(context::jq -r --argjson config "$cluster_config_json" '.review.request.objects//[] | map(
     if .apiVersion == "deckhouse.io/v1alpha2" then
       .apiVersion = "deckhouse.io/v1" |
       .metadata.name as $ngName |
       .spec.nodeType |=
          if . == "Cloud" then "CloudEphemeral"
            elif . == "Static" then "Static"
            elif . == "Hybrid" then
              if ($config | .nodeGroups += [{"name": "master"}] | .nodeGroups[] | select($ngName == .name)) // false then
                "CloudPermanent"
              else
                "CloudStatic"
              end
            else .
        end
     else . end
  )')
  then
    cat <<EOF >"$CONVERSION_RESPONSE_PATH"
{"convertedObjects": $converted}
EOF
  else
    cat <<EOF >"$CONVERSION_RESPONSE_PATH"
{"failedMessage":"Conversion of nodegroups.deckhouse.io failed"}
EOF
  fi
}

function __on_conversion::v1_to_alpha2() {
  if converted=$(context::jq -r '.review.request.objects//[] | map(
     if .apiVersion ==  "deckhouse.io/v1" then
       .apiVersion = "deckhouse.io/v1alpha2" |
       .spec.nodeType |=
          if . == "CloudEphemeral" then "Cloud"
            elif . == "CloudPermanent" or . == "CloudStatic" then "Hybrid"
            elif . == "Static" then "Static"
            else .
          end
     else . end
  )')
  then
    cat <<EOF >"$CONVERSION_RESPONSE_PATH"
{"convertedObjects": $converted}
EOF
  else
    cat <<EOF >"$CONVERSION_RESPONSE_PATH"
{"failedMessage":"Conversion of nodegroups.deckhouse.io failed"}
EOF
  fi
}

hook::run "$@"
